package com.ciwong.epaper.modules.me.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.ExpandableListView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.bookstore.adapter.GroupingStuAdapter;
import com.ciwong.epaper.modules.bookstore.bean.StudentGroupBean;
import com.ciwong.epaper.modules.clazz.bean.StudentBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description:学生分组集合页面
 * @author: wyk
 * @time: 2021/5/24 16:10
 */
public class GroupingStudentActivity extends BaseActivity {

    private ExpandableListView grouping_stu_list;

    //学生集合
    private List<StudentBean> studentBeans;
    //年级id
    private int gradeId;
    private String clientId;
    //班级id
    private int classId;
    //班级名
    private String className;
    //学校名
    private String schoolName;
    //vip人数
    private int vipCount;
    //学生人数
    private int stuCount;
    private int JUMP_TO_UPDATE_CLASS_NAME = 10001;
    private int JUMP_TO_MEMBER = 10002;
    /**
     * 是否分组
     */
    private Boolean isGrouping;
    //分组学生集合
    private List<StudentGroupBean> studentGroupBeanList;
    private GroupingStuAdapter groupingStuAdapter;
    //是否修改班级名
    private Boolean upeClassNameSuccess = false;

    @Override
    protected int setView() {
        return R.layout.activity_grouping_stu;
    }

    @Override
    protected void findViews() {
        grouping_stu_list = findViewById(R.id.grouping_stu_list);
    }

    @Override
    protected void initEvent() {

        grouping_stu_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                if (i < studentGroupBeanList.size()) {
                    List<StudentBean> list = studentGroupBeanList.get(i).getList();
                    String teamName = null;
                    int teamId = 0;
                    if (list.size() > 0) {
                        teamName = list.get(0).getTeamName();
                        teamId = list.get(0).getTeamId();
                    }
                    if (null == teamName || "".equals(teamName)) {
                        isGrouping = false;
                    } else {
                        isGrouping = true;
                    }
                    MeJumpManager.jumpToMembersActivity(className, clientId, classId, isGrouping, teamId, teamName, JUMP_TO_MEMBER, GroupingStudentActivity.this);
                }
                return true;
            }
        });
        setRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                MeJumpManager.jumpToUpeClassName(stuCount, vipCount, schoolName, className, gradeId, classId, JUMP_TO_UPDATE_CLASS_NAME, GroupingStudentActivity.this);
            }
        });
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        clientId = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLIENT_ID);
        classId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CLASS_ID, 0);
        className = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_NAME);
        schoolName = intent.getStringExtra(IntentFlag.INTENT_FLAG_SCHOOL_NAME);
        gradeId = intent.getIntExtra(IntentFlag.INTENT_FLAG_GRADE_ID, 0);
        setTitleText(className);
        setRightBtnText("修改");
        groupingStuAdapter = new GroupingStuAdapter(studentGroupBeanList, GroupingStudentActivity.this, classId);
        grouping_stu_list.setAdapter(groupingStuAdapter);
    }

    @Override
    protected void loadData() {
        showCricleProgress();
        try {
            getMembers(classId, clientId, 1, 1, 1);
        } catch (Exception e) {

        }

    }

    /**
     * 获取班级成员
     *
     * @param classId     班级id
     * @param clientId
     * @param getIntegral
     * @param getVip
     * @param role
     */
    public void getMembers(int classId, String clientId, int getIntegral, int getVip, int role) {

        EpaperDao.getInstance().getmembers(classId, clientId, getIntegral, getVip, role, new BaseExtCallBack(GroupingStudentActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {

                hideCricleProgress();
                if (null != data && data instanceof ArrayList) {
                    studentBeans = (List<StudentBean>) data;
                    stuCount = studentBeans.size();
                    studentGroupBeanList = new ArrayList<>();
                    Map<Integer, String> map = new HashMap<>();
                    for (StudentBean stu : studentBeans) {
                        if (stu.getIsVip() == 1) {
                            vipCount++;
                        }
                        map.put(stu.getTeamId(), stu.getTeamName());
                    }
                    Set<Integer> integers = map.keySet();
                    for (Integer integer : integers) {
                        StudentGroupBean studentGroupBean = new StudentGroupBean();
                        List<StudentBean> stuList = new ArrayList<>();
                        int checkCount = stuList.size();
                        for (int i = 0; i < studentBeans.size(); i++) {
                            if (studentBeans.get(i).getTeamId() == integer) {
                                stuList.add(studentBeans.get(i));
                            }
                        }
                        studentGroupBean.setList(stuList);
                        studentGroupBean.setCheckCount(0);
                        studentGroupBeanList.add(studentGroupBean);
                    }
                    groupingStuAdapter.setNewData(studentGroupBeanList);
                    for (int i = 0; i < studentGroupBeanList.size(); i++) {
                        grouping_stu_list.expandGroup(i);
                    }

                }

            }
        });
    }

    /**
     * 老师重置密码
     *
     * @param classId
     * @param userId
     * @param password
     */
    public void setUserPassWord(int classId, int userId, final String userName, final String password) {
        showCricleProgress();
        EpaperDao.getInstance().setUserPassWord(classId, userId, password, new BaseExtCallBack(GroupingStudentActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data && data instanceof Boolean) {
                    Boolean reult = (Boolean) data;
                    if (reult) {
                        ToastUtil.INSTANCE.toastCenter(GroupingStudentActivity.this, "重置密码成功 " + userName + " 密码:" + password);
                        return;
                    }
                }
                ToastUtil.INSTANCE.toastCenterError(getString(R.string.set_password_faild_try_later));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            if (JUMP_TO_UPDATE_CLASS_NAME == requestCode) {
                className = data.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_NAME);
                setTitleText(className);
                upeClassNameSuccess = true;
            } else if (JUMP_TO_MEMBER == requestCode) {
                //修改班级分组成功 重新加载页面
                loadData();
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    private CWDialog cwDialog;

    /**
     * 清零小红花提示框
     */
    public void showClearUserFlowerDialog(final StudentBean mStudentBean) {
        if (null != cwDialog && cwDialog.isShowing()) {
            cwDialog.dismiss();
        }
        cwDialog = new CWDialog(GroupingStudentActivity.this);
        cwDialog.setTitle(R.string.str_hint);
        cwDialog.setMessagWidePadding("确定清零" + mStudentBean.getUserName() + "的小红花?")
                .setPositiveButton(R.string.str_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        clearUserFlower(mStudentBean);
                    }
                }).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                cwDialog.dismiss();
            }
        }).show();

        cwDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cwDialog.dismiss();
            }
        });
    }

    /**
     * 清零小红花
     *
     * @param mStudentBean
     */
    public void clearUserFlower(final StudentBean mStudentBean) {
        showCricleProgress(null);
        int[] userIds = {mStudentBean.getUserId()};
        MeDao.getInstance().deductdall(userIds,
                new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        hideCricleProgress();

                    }

                    @Override
                    public void failed(Object data) {
                        hideCricleProgress();
                    }

                    @Override
                    public void success(Object data) {
                        hideCricleProgress();
                        loadData();
                        ToastUtil.INSTANCE.toastCenter(GroupingStudentActivity.this,
                                "清理" + mStudentBean.getUserName() + " 账号:" + mStudentBean.getUserId() + "小红花成功。");
                    }
                });

    }
}
